<template>
  <WindowDialog v-model:visible="show" title="视频回放" @close="close">
    <div class="video-windows">
      <jessibucaPlayer
        ref="jessibucaRef"
        :videoUrl="videoUrl"
        :error="videoError"
        :message="videoError"
        :hasAudio="hasAudio"
        domId="play_back_video"
        fluent
        autoplay
        live
      />
    </div>
    <div class="ctrl-list">
      <!-- 日期选择 -->
      <a-date-picker style="width: 200px" v-model:value="time" @change="timeChange" />
      <!-- 控制按钮 -->
      <div class="button-list">
        <div class="button-item" @click="play">开 始</div>
        <div class="button-item" @click="pause">暂 停</div>
        <div class="button-item" @click="download">下 载</div>
      </div>
    </div>
    <!-- 时间条 -->
    <div class="progress-bar">
      <ProgressBar ref="progressBarRef" @updateTime="updateTime" />
    </div>
  </WindowDialog>
</template>

<script setup>
  import { ref } from 'vue';
  import { api as playbackApi } from '/@/api/wvp/playback.js';
  import WindowDialog from '/@/components/windowDialog/index.vue';
  import jessibucaPlayer from '/@/components/jessibuca/playBack.vue';
  import ProgressBar from './progressBar.vue';
  import { dateFormat } from '/@/utils/date';
  import dayjs from 'dayjs';

  const emits = defineEmits(['download']);

  const jessibucaRef = ref();
  const progressBarRef = ref();
  const show = ref(false);
  const videoUrl = ref('');
  const hasAudio = ref(false);
  const time = ref(undefined);
  let startTime = '';
  let endTime = '';
  let playbackStreamUrl = '';
  const format = 'YYYY-MM-DD';

  const videoError = function (e) {
    console.log('播放器错误：' + JSON.stringify(e));
  };

  function open(url) {
    show.value = true;
    playbackStreamUrl = url;
    changeDay();
  }

  function timeChange(val) {
    stop();
    changeDay(val);
  }

  function changeDay(val = new Date()) {
    const thisDay = dateFormat(val);
    time.value = dayjs(thisDay, format);
    initTime();
  }

  function initTime() {
    // 从每天的0点开始播放
    startTime = dateFormat(time.value, 'yyyy-MM-dd') + ' 00:00:00';
    // endTime需要判断日期是不是今天
    if (dateFormat(time.value, 'yyyy-MM-dd') === dateFormat(new Date(), 'yyyy-MM-dd')) {
      // 如果是今天，只能看半小时前
      endTime = dateFormat(time.value, 'yyyy-MM-dd') + dateFormat(+new Date() - 10 * 60 * 1000, ' hh:mm:ss');
    } else {
      endTime = dateFormat(time.value, 'yyyy-MM-dd') + ' 23:59:59';
    }
    progressBarRef.value.initProgress({ startTime, endTime });
    getPlayUrl();
  }

  function updateTime(val, type) {
    if (type === 'active' && show.value) {
      console.log('startTime: ', startTime);
      stop();
      startTime = val;
      endTime = dateFormat(time.value, 'yyyy-MM-dd') + ' 23:59:59';
      getPlayUrl();
    }
  }

  function getPlayUrl() {
    playbackApi
      .getVideoUrl({
        url: playbackStreamUrl,
        startTime,
        endTime,
      })
      .then(({ data }) => {
        hasAudio.value = true;
        videoUrl.value = data.ws_flv.replace('ws://192.168.1.111:80', 'wss://101.66.174.148:9089/live');
      });
  }

  async function stop() {
    // 调用stop，停止拉流
    const formatDate = (dateString) => dateString.replace(/[-: ]/g, '');
    const formattedB = formatDate(startTime);
    const formattedC = formatDate(endTime);
    const result = `${playbackStreamUrl}/${playbackStreamUrl.replace(/\//g, '_')}_${formattedB}_${formattedC}`;
    await playbackApi.stopPlayBack(result);
    videoUrl.value = null;
    hasAudio.value = false;
  }

  function close() {
    stop();
    playbackStreamUrl = '';
    progressBarRef.value.stop();
  }

  function play() {
    jessibucaRef.value.playBtnClick();
  }

  function pause() {
    jessibucaRef.value.pause();
  }

  function download() {
    emits('download');
  }

  defineExpose({ open });
</script>

<style scoped lang="less">
  .video-windows {
    width: 100%;
    height: calc(100vh - 150px);
    background-color: #fff;
  }
  .ctrl-list {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    .button-list {
      display: flex;
      margin-left: 15px;
      .button-item {
        background-color: #ffffff;
        border-color: #d9d9d9;
        box-shadow: 0 2px 0 rgba(0, 0, 0, 0.02);
        font-size: 14px;
        height: 32px;
        padding: 4px 15px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        border: 1px solid #ddd;
        border-left: 1px;
        &:hover {
          color: #4096ff;
          border-color: #4096ff;
        }
        &:first-of-type {
          border-radius: 6px 0 0 6px;
        }
        &:last-of-type {
          border-radius: 0 6px 6px 0;
        }
      }
    }
  }
  .progress-bar {
    padding: 0 5px;
  }
</style>
